import React, { useState } from 'react';
import {
  Card,
  Statistic,
  Row,
  Col,
  DatePicker,
  Select,
  Tabs,
  Table,
  Tag,
  Progress,
  Space,
  List,
  Avatar,
} from 'antd';
import { useNavigate } from 'react-router-dom';
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  DollarOutlined,
  UserOutlined,
  CalendarOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import Layout from '../../components/Layout';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 模拟收入数据
const mockIncomeData = [
  { month: '1月', income: 45000, outpatient: 28000, surgery: 17000 },
  { month: '2月', income: 52000, outpatient: 32000, surgery: 20000 },
  { month: '3月', income: 48000, outpatient: 30000, surgery: 18000 },
  { month: '4月', income: 60000, outpatient: 35000, surgery: 25000 },
  { month: '5月', income: 65000, outpatient: 38000, surgery: 27000 },
  { month: '6月', income: 70000, outpatient: 40000, surgery: 30000 },
];

// 模拟患者数据
const mockPatientData = [
  { month: '1月', newPatients: 80, returnPatients: 120, total: 200 },
  { month: '2月', newPatients: 95, returnPatients: 130, total: 225 },
  { month: '3月', newPatients: 90, returnPatients: 135, total: 225 },
  { month: '4月', newPatients: 105, returnPatients: 150, total: 255 },
  { month: '5月', newPatients: 110, returnPatients: 160, total: 270 },
  { month: '6月', newPatients: 120, returnPatients: 175, total: 295 },
];

// 模拟工作量数据
const mockWorkloadData = [
  { month: '1月', outpatient: 180, surgery: 45, consultation: 60 },
  { month: '2月', outpatient: 200, surgery: 50, consultation: 70 },
  { month: '3月', outpatient: 190, surgery: 48, consultation: 65 },
  { month: '4月', outpatient: 210, surgery: 55, consultation: 75 },
  { month: '5月', outpatient: 220, surgery: 60, consultation: 80 },
  { month: '6月', outpatient: 230, surgery: 65, consultation: 85 },
];

// 模拟收入明细数据
const mockIncomeDetail = [
  { id: '1', patient: '张三', date: '2024-06-15', type: '门诊', amount: 350.5, status: '已结算' },
  { id: '2', patient: '李四', date: '2024-06-14', type: '手术', amount: 5600.0, status: '已结算' },
  { id: '3', patient: '王五', date: '2024-06-14', type: '检查', amount: 800.0, status: '已结算' },
  { id: '4', patient: '赵六', date: '2024-06-13', type: '门诊', amount: 280.0, status: '已结算' },
  { id: '5', patient: '钱七', date: '2024-06-12', type: '手术', amount: 4200.0, status: '待结算' },
  { id: '6', patient: '孙八', date: '2024-06-12', type: '门诊', amount: 320.0, status: '已结算' },
];

const Statistics: React.FC = () => {
  const navigate = useNavigate();
  const [dateRange, setDateRange] = useState<any[]>([]);
  const [viewType, setViewType] = useState('month');
  const [selectedMonth, setSelectedMonth] = useState('6月');

  // 计算当月总收入
  const currentMonthIncome = mockIncomeData.find(item => item.month === selectedMonth)?.income || 0;
  const totalIncome = mockIncomeData.reduce((sum, item) => sum + item.income, 0);
  const totalPatients = mockPatientData.reduce((sum, item) => sum + item.total, 0);
  const totalWorkload = mockWorkloadData.reduce((sum, item) => sum + item.outpatient + item.surgery + item.consultation, 0);

  // 收入表格列定义
  const incomeColumns = [
    {
      title: '患者姓名',
      dataIndex: 'patient',
      key: 'patient',
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={
          type === '门诊' ? 'blue' : 
          type === '手术' ? 'red' : 'green'
        }>
          {type}
        </Tag>
      ),
    },
    {
      title: '金额(元)',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '已结算' ? 'success' : 'processing'}>
          {status}
        </Tag>
      ),
    },
  ];

  // 模拟图表数据（简化版，实际应使用ECharts）
  const renderChart = (type: string) => {
    let data;
    switch (type) {
      case 'income':
        data = mockIncomeData;
        break;
      case 'patient':
        data = mockPatientData;
        break;
      case 'workload':
        data = mockWorkloadData;
        break;
      default:
        data = mockIncomeData;
    }

    return (
      <div style={{ height: 300, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around', padding: '20px' }}>
        {data.map((item, index) => {
          let value = type === 'income' ? item.income : 
                      type === 'patient' ? item.total : 
                      item.outpatient + item.surgery + item.consultation;
          
          return (
            <div key={index} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div
                style={{
                  width: 40,
                  backgroundColor: '#1890ff',
                  transition: 'height 0.3s',
                  height: Math.min((value / Math.max(...data.map(d => 
                    type === 'income' ? d.income : 
                    type === 'patient' ? d.total : 
                    d.outpatient + d.surgery + d.consultation
                  ))) * 200, 200),
                }}
              />
              <div style={{ marginTop: 8, fontSize: 12 }}>{item.month}</div>
              <div style={{ marginTop: 4, fontSize: 12, color: '#666' }}>
                {type === 'income' ? `¥${value.toLocaleString()}` : value}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // 目标完成度数据
  const targets = [
    { name: '月度收入目标', current: 70000, target: 80000, unit: '元' },
    { name: '月度门诊量', current: 230, target: 250, unit: '人次' },
    { name: '月度手术量', current: 65, target: 60, unit: '台' },
  ];

  return (
    <Layout title="业绩统计" showBackButton>
      {/* 统计筛选条件 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col>
            <span style={{ marginRight: 8 }}>统计周期：</span>
            <RangePicker onChange={(dates) => setDateRange(dates || [])} />
          </Col>
          <Col>
            <span style={{ marginRight: 8 }}>视图类型：</span>
            <Select 
              value={viewType} 
              onChange={setViewType}
              style={{ width: 120 }}
            >
              <Option value="day">日</Option>
              <Option value="month">月</Option>
              <Option value="quarter">季度</Option>
              <Option value="year">年</Option>
            </Select>
          </Col>
          <Col>
            {viewType === 'month' && (
              <>
                <span style={{ marginRight: 8 }}>选择月份：</span>
                <Select 
                  value={selectedMonth} 
                  onChange={setSelectedMonth}
                  style={{ width: 100 }}
                >
                  {['1月', '2月', '3月', '4月', '5月', '6月'].map(month => (
                    <Option key={month} value={month}>{month}</Option>
                  ))}
                </Select>
              </>
            )}
          </Col>
        </Row>
      </Card>

      {/* 关键指标卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="当月总收入"
              value={currentMonthIncome}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#3f8600' }}
              precision={2}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="累计总收入"
              value={totalIncome}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#1677ff' }}
              precision={2}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="累计患者数"
              value={totalPatients}
              prefix={<UserOutlined />}
              suffix="人次"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="累计工作量"
              value={totalWorkload}
              prefix={<CheckCircleOutlined />}
              suffix="次"
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 目标完成度 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        {targets.map((target, index) => (
          <Col xs={24} md={8} key={index}>
            <Card>
              <div style={{ marginBottom: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span>{target.name}</span>
                  <span>
                    {target.current} / {target.target} {target.unit}
                  </span>
                </div>
                <Progress
                  percent={(target.current / target.target) * 100}
                  strokeColor={{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }}
                />
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 详细统计标签页 */}
      <Tabs defaultActiveKey="1" type="card">
        <TabPane tab={<span><BarChartOutlined /> 收入统计</span>} key="1">
          <Card>
            {renderChart('income')}
            <Row gutter={16}>
              {mockIncomeData.map((item, index) => (
                <Col xs={24} sm={12} md={8} key={index}>
                  <Card>
                    <div style={{ marginBottom: 8 }}><strong>{item.month}收入明细</strong></div>
                    <List
                      size="small"
                      dataSource={[
                        { type: '门诊收入', value: item.outpatient },
                        { type: '手术收入', value: item.surgery },
                      ]}
                      renderItem={(data) => (
                        <List.Item>
                          <List.Item.Meta
                            title={
                              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span>{data.type}</span>
                                <span>¥{data.value.toLocaleString()}</span>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontWeight: 'bold' }}>
                      <span>合计：</span>
                      <span>¥{item.income.toLocaleString()}</span>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </TabPane>

        <TabPane tab={<span><UserOutlined /> 患者统计</span>} key="2">
          <Card>
            {renderChart('patient')}
            <Row gutter={16}>
              {mockPatientData.map((item, index) => (
                <Col xs={24} sm={12} md={8} key={index}>
                  <Card>
                    <div style={{ marginBottom: 8 }}><strong>{item.month}患者明细</strong></div>
                    <List
                      size="small"
                      dataSource={[
                        { type: '新患者', value: item.newPatients },
                        { type: '复诊患者', value: item.returnPatients },
                      ]}
                      renderItem={(data) => (
                        <List.Item>
                          <List.Item.Meta
                            title={
                              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span>{data.type}</span>
                                <span>{data.value} 人次</span>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontWeight: 'bold' }}>
                      <span>合计：</span>
                      <span>{item.total} 人次</span>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </TabPane>

        <TabPane tab={<span><ClockCircleOutlined /> 工作量统计</span>} key="3">
          <Card>
            {renderChart('workload')}
            <Row gutter={16}>
              {mockWorkloadData.map((item, index) => (
                <Col xs={24} sm={12} md={8} key={index}>
                  <Card>
                    <div style={{ marginBottom: 8 }}><strong>{item.month}工作量明细</strong></div>
                    <List
                      size="small"
                      dataSource={[
                        { type: '门诊', value: item.outpatient },
                        { type: '手术', value: item.surgery },
                        { type: '咨询', value: item.consultation },
                      ]}
                      renderItem={(data) => (
                        <List.Item>
                          <List.Item.Meta
                            title={
                              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span>{data.type}</span>
                                <span>{data.value} 次</span>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontWeight: 'bold' }}>
                      <span>合计：</span>
                      <span>{item.outpatient + item.surgery + item.consultation} 次</span>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </TabPane>

        <TabPane tab={<span><DollarOutlined /> 收入明细</span>} key="4">
          <Card>
            <Table
              columns={incomeColumns}
              dataSource={mockIncomeDetail}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>
      </Tabs>
    </Layout>
  );
};

export default Statistics;